<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>

        // 创建Canvas元素
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');

        // 设置画布尺寸
        canvas.width = 120;
        canvas.height = 40;

        // 定义验证码的字符集合
        var charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        // 生成随机四位验证码
        var captcha = '';
        for (var i = 0; i < 4; i++) {
            var randomIndex = Math.floor(Math.random() * charset.length);
            captcha += charset[randomIndex];
        }

        // 绘制背景
        ctx.fillStyle = '#f5f5f5';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 绘制文字
        ctx.font = 'bold 24px Arial';
        ctx.fillStyle = '#333';
        ctx.textBaseline = 'middle';
        ctx.fillText(captcha, 20, canvas.height / 2);

        // 绘制干扰线
        for (var i = 0; i < 4; i++) {
            ctx.strokeStyle = 'rgba(0, 0, 0, 0.2)';
            ctx.beginPath();
            ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
            ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
            ctx.stroke();
        }

        // 将Canvas转换为图片URL
        var dataURL = canvas.toDataURL();

        // 创建验证码图片元素
        var img = document.createElement('img');
        img.src = dataURL;

        // 将图片元素添加到DOM中
        document.body.appendChild(img);

    </script>
</body>

</html>